#include "Access.h"
Access &Access::getInstance() {
  static Access instance;
  return instance;
}
Access::Access() {
  /* 临时地存储------------------------------------------------------------------------------------------------ */
Serial.print("Access初始化本地数据");
  /* 若密钥为空设置默认密钥-----------------程序成熟后删除 */
 if(localStorage.getItem("key")=="")localStorage.setItem("key", "[{\"username\":\"LIUBO\",\"password\":\"01221204a\"},{\"username\":\"刘波\",\"password\":\"01221204b\"},{\"username\":\"刘菲菲\",\"password\":\"01221204c\"}]");
 Serial.println(localStorage.getItem("key"));
  KeyArray = JSON.parse(localStorage.getItem("key"));
}
/* 私有函数通用匹配密钥 */
bool Access::matchKey(const String &key, const String &value) {
  //KeyArray = JSON.parse(localStorage.getItem("key"));
  if (JSON.typeof(KeyArray) != "array" || value=="") {
    return false;
  }
  for (int i = 0; i < KeyArray.length(); i++) {
    if ((String)KeyArray[i][key] == value) {
      return true;  // 找到匹配
    }
  }
  return false;  // 没有找到匹配
}

// 调用通用函数，检查用户名和密码匹配
bool Access::userMatching(const String &username, const String &password) {

  return matchKey("username", username) && matchKey("password", password);
}

// 调用通用函数，检查用户密钥匹配
bool Access::keyMatching(const String &userkey) {
  return matchKey("userkey", userkey);
}
String Access::changekey(const String &userkey) {  //根据用户的userkey值随机变换其值
  if (JSON.typeof(KeyArray) != "array") {
    //Serial.println("changekey 没有找到KeyArray!");
    return "";
  }
  for (int i = 0; i < KeyArray.length(); i++) {
    if ((String)KeyArray[i]["userkey"] == userkey) {
      String jsonkey = "{\"username\":\"" + (String)KeyArray[i]["username"] + "\",\"password\":\"" + (String)KeyArray[i]["password"] + "\"}" + String(random(100000, 1000000));  //密钥原始字符串
      //JSONVar newUser = JSON.parse("{\"username\":\"" + (String)KeyArray[i]["username"] + "\",\"password\":\"" + (String)KeyArray[i]["password"] + "\",\"userkey\":\"" + md5_string((char *)jsonkey.c_str()) + "\"}");
      KeyArray[i]["userkey"] = md5_string((char *)jsonkey.c_str());
      //KeyArray[i] = newUser;
      localStorage.setItem("key", JSON.stringify(KeyArray));
      return (String)KeyArray[i]["userkey"];
    }
  }
  return "";  // 没有找到匹配
}
/* 寻找传入的用户名密码完全相同的用户并返回密钥 */
String Access::readkey(const String &username, const String &password) {
  if (JSON.typeof(KeyArray) != "array" || !KeyArray.length()) {
    Serial.println("readkey Parsing control undefined!");
    return "";
  }

  for (int i = 0; i < KeyArray.length(); i++) {
    if ((String)KeyArray[i]["username"] == username) {
      if ((String)KeyArray[i]["password"] == password) {
        return (String)KeyArray[i]["userkey"];
      }
      return "";
    }
  }
  return "";
}

void Access::add(const String &username, const String &password) {
  KeyArray = JSON.parse(localStorage.getItem("key"));
  String jsonkey = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}" + String(random(100000, 1000000));//密钥原始字符串
  JSONVar newUser = JSON.parse("{\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"userkey\":\"" + md5_string((char *)jsonkey.c_str()) + "\"}");
  //Serial.printf("\ntextJSON=%s--+++++++++++++++++++++++++++++-----", JSON.stringify(newUser).c_str());
  if (!KeyArray.length()) {
    KeyArray[0] = newUser;
  } else {
    /* 寻找匹配项并赋值 */
    for (int i = 0; i < KeyArray.length(); i++) {
      if ((String)KeyArray[i]["username"] == username) {
        KeyArray[i] = newUser;
        localStorage.setItem("key", JSON.stringify(KeyArray));
        return;
      }
    }
    /* 若未找到将会在末尾赋值 */
    KeyArray[KeyArray.length()] = newUser;
  }
  localStorage.setItem("key", JSON.stringify(KeyArray));
}
/* 删除指定用户名的密钥 */
void Access::del(const String &username) {
  KeyArray = JSON.parse(localStorage.getItem("key"));
  int newLength = 0;
  // 创建一个新数组
  JSONVar newArray;
  JSONVar newObject;

  for (int i = 0; i < KeyArray.length(); i++) {
    if ((String)KeyArray[i]["username"] != username) {
      Serial.printf("\nKeyArray[%d]=%s", i, JSON.stringify(KeyArray[i]).c_str());
      newObject = KeyArray[i];            //不间接赋值会出错；
      newArray[newLength++] = newObject;  // 仅保留不匹配的用户
    }
  }
  // 更新 KeyArray 和存储

  Serial.printf("\nKeyArray:%s,newArray:%s", JSON.stringify(KeyArray).c_str(), JSON.stringify(newArray).c_str());
  KeyArray = newArray;
  localStorage.setItem("key", JSON.stringify(KeyArray));  // 更新存储
}